package com.yunshipei.core.ui.client;

import android.net.Uri;
import android.text.TextUtils;
import android.webkit.ValueCallback;

import org.xwalk.core.XWalkJavascriptResult;
import org.xwalk.core.XWalkUIClient;
import org.xwalk.core.XWalkView;

public final class EnterWebChromeClient extends XWalkUIClient {

    private ValueCallback<Uri> mUploadMessage;
    private OnEnterWebChromeClientInteractionListener mWebChromeClientInteractionListener;

    public EnterWebChromeClient(XWalkView view, OnEnterWebChromeClientInteractionListener webChromeClientInteractionListener) {
        super(view);
        this.mWebChromeClientInteractionListener = webChromeClientInteractionListener;
    }

    @Override
    public void onJavascriptCloseWindow(XWalkView view) {
        if (mWebChromeClientInteractionListener != null) {
            mWebChromeClientInteractionListener.closeWindow();
        }
    }

    @Override
    public boolean onConsoleMessage(XWalkView view, java.lang.String message, int lineNumber, java.lang.String sourceId, XWalkUIClient.ConsoleMessageType messageType) {
        return super.onConsoleMessage(view, message, lineNumber, sourceId, messageType);
    }

    @Override
    public void onPageLoadStopped(XWalkView view, String url, LoadStatus status) {
        if (mWebChromeClientInteractionListener != null) {
            mWebChromeClientInteractionListener.updateProgress(100);
        }
    }

    @Override
    public void openFileChooser(XWalkView view, ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
        if (mWebChromeClientInteractionListener != null) {
            mUploadMessage = uploadMsg;
            mWebChromeClientInteractionListener.openFileChooser();
        }
    }

    @Override
    public boolean onJsConfirm(XWalkView view, String url, String message, XWalkJavascriptResult result) {
        if (TextUtils.isEmpty(message)) {
            result.confirm();
            return true;
        }
        return super.onJsConfirm(view, url, message, result);
    }

    @Override
    public boolean onJsPrompt(XWalkView view, String url, String message, String defaultValue, XWalkJavascriptResult result) {
        return super.onJsPrompt(view, url, message, defaultValue, result);
    }

    public ValueCallback<Uri> getValueCallback() {
        return this.mUploadMessage;
    }

    public interface OnEnterWebChromeClientInteractionListener {
        void closeWindow();

        void updateProgress(int progress);

        void openFileChooser();
    }
}
